﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HelperPrototype.Properties;
using System.Data.SqlClient;

namespace HelperPrototype.OtherForms
{
    public partial class SettingForm : Form
    {
        public SettingForm()
        {
            InitializeComponent();
        }

        private void Setting_Load(object sender, EventArgs e)
        {
            loadData();
        }

        void loadData()
        {
            // parse connection string
            String connectionString =
                Settings.Default.myConnectionString;
            SqlConnectionStringBuilder builder =
                new SqlConnectionStringBuilder(connectionString);

            // show on form
            txtServer.Text = builder.DataSource;
            txtDatabase.Text = builder.InitialCatalog;
            txtUsername.Text = builder.UserID;
            txtPassword.Text = builder.Password;
        }

        private String getConnectionString()
        {
            SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
            builder.DataSource = txtServer.Text;
            builder.InitialCatalog = txtDatabase.Text;
            builder.UserID = txtUsername.Text;
            builder.Password = txtPassword.Text;
            return builder.ConnectionString;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Settings.Default.myConnectionString = getConnectionString();
            Settings.Default.Save();
            this.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            /*
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = getConnectionString();
            cn.Open();
            MessageBox.Show(cn.State.ToString());*/

            try
            {
                using (SqlConnection conn = new SqlConnection(getConnectionString()))
                {
                    conn.Open();
                    conn.Close();
                }

                MessageBox.Show("Connection OK!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Message);
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            loadData();
        }
    }
}
